<template>
	<section >
		<!--工具条 高级查询 新增数据-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
        <el-button type="danger" @click="batchRemove" :disabled="this.handleSelectValue.length===0">批量删除</el-button>
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字" size="medium" prefix-icon="el-icon-search" clearable></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search" size="medium" prefix-icon="el-icon-search" clearable>查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" size="medium" prefix-icon="el-icon-search" clearable>新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAssignClue">分配线索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleConvertOpportunities">转化商机</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表 编辑 删除-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="handleSelectionChange" style="width: 100%;">
			<el-table-column type="selection" width="50">
			</el-table-column>
			<el-table-column type="index" width="50">
			</el-table-column>
			<el-table-column prop="fullName" label="姓名" width="50" sortable>
			</el-table-column>
			<el-table-column prop="appellation" label="别名" width="50" sortable>
			</el-table-column>
			<el-table-column prop="company" label="公司" width="50" sortable>
			</el-table-column>
			<el-table-column prop="job" label="职位" width="50" sortable>
			</el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="100" sortable>
      </el-table-column>
			<el-table-column prop="phone" label="电话" min-width="100" sortable>
			</el-table-column>
			<el-table-column prop="mphone" label="移动电话" min-width="100" sortable>
			</el-table-column>
			<el-table-column prop="address" label="住址" min-width="100" sortable>
			</el-table-column>
			<el-table-column prop="source" label="客户来源" min-width="100" sortable>
			</el-table-column>
			<el-table-column prop="seller.username" label="所属员工" min-width="100" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == -1" style="color: red">释放到线索池</span>
          <span v-if="scope.row.state == 0" style="color: gray">未分配</span>
          <span v-if="scope.row.state == 1" style="color: green">跟进中</span>
          <span v-if="scope.row.state == 2" style="color: yellow">成为商机</span>
        </template>
			</el-table-column>
      <el-table-column prop="createBy" label="创建人" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="editBy" label="编辑人" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="editTime" label="编辑时间" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="description" label="客户意向" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="contactSummary" label="跟进类容" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="nextContactTime" label="下次联系时间" min-width="100" sortable>
      </el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
<!--          关联活动就是客户看上了哪个优惠活动-->
					<el-button size="small" @click="handleClueActivity(scope.$index, scope.row)">关联活动</el-button>
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
    </el-table>
		<!--工具条 批量删除 分页查询-->
		<el-col :span="24" class="toolbar">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>
		<!--新增和修改模态框界面-->
		<el-dialog title="新增/修改" :visible.sync ="clueFormVisible" :close-on-click-modal="false">
			<el-form :model="clueForm" label-width="80px" :rules="addFormRules" ref="clueForm">
				<el-form-item label="姓名" prop="fullName">
					<el-input v-model="clueForm.fullName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门经理" >
<!--					<el-input v-model="clueForm.manager.id" auto-complete="off"></el-input>-->
          <el-select v-model="clueForm.seller" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="clueForm.state">
						<el-radio class="radio" :label="-1">释放到线索池</el-radio>
						<el-radio class="radio" :label="0">未分配</el-radio>
						<el-radio class="radio" :label="1">跟进中</el-radio>
						<el-radio class="radio" :label="2">成为商机</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="公司">
					<el-input  v-model="clueForm.company"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="clueFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
<!--    绑定活动的弹框-->
    <el-dialog title="添加活动" :visible.sync="clueActivityVisible" :close-on-click-modal="false">
      <el-form :model="clueActivity" label-width="80px" :rules="clueFormRules" ref="clueActivity">
        <el-form-item label="营销活动">
          <el-checkbox-group v-model="clueActivity.activityIds">
            <el-checkbox v-for="a in activities" :label="a.id">{{a.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="clueActivityVisible = false">取消</el-button>
        <el-button type="primary" @click.native="clueActivitySubmit" :loading="clueFormLoading">提交</el-button>
      </div>
    </el-dialog>
<!--    分配线索给公司员工-->
    <el-dialog title="分配线索" :visible.sync="clueAssignVisible" :close-on-click-modal="false">
      <el-form :model="clueForm" label-width="80px" :rules="clueFormRules" ref="clueActivity">
        <el-form-item label="名称" prop="fullName">
          <el-input v-model="clueForm.fullName" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="clueForm.phone" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="营销人员">
          <el-select v-model="clueForm.seller" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="clueAssignVisible = false">取消</el-button>
        <el-button type="primary" @click.native="clueAssignSubmit" :loading="clueFormLoading">提交</el-button>
      </div>
    </el-dialog>
<!--    将线索转换为商机，就是客户看上哪个产品了，将这个信息记录在后端数据库-->
    <el-dialog title="转化商机" :visible.sync="clueBusinessVisible" :close-on-click-modal="false">
      <el-form :model="businessData" label-width="80px" :rules="clueFormRules" ref="clueActivity">
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="businessData.clue.fullName" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="businessData.clue.phone" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="businessData.product" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="clueBusinessVisible = false">取消</el-button>
        <el-button type="primary" @click.native="clueBusinessSubmit" :loading="businessFormLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
			  /*转化商机
			  * */
        clueBusinessVisible: false,//转化商机的弹窗
        //转化商机弹窗表单所需要的数据
        businessData: {
          clue: {
            id: null,
            fullName: '',
            company: '',
            seller: {//营销人员
              id: null
            }
          },
          product: {
            id: null,
            name: '',
            price: null
          }

        },
        products: [],//转化商机所需要的产品信息
        businessFormLoading: false,//转化商机页面加载等待


			  employees: [],//用来接收所有员工
        activities: [],//用来装所有的活动
        clueActivity: {
			    clueId: null,//线索id
          activityIds: []//活动id
        },
				query: {
					currentPage: 1,
          pageSize: 10,
          keyword: ""
				},
				pageInfo: {
				  total: 0,//分页查询总条数
          rows: []//当前页展示数据
        },

				listLoading: false,//渲染列表页面时加载等待
        saveLoading: false,//保存页面时加载等待
        clueFormLoading: false,//绑定活动时加载等待

				handleSelectValue: [],//里面装的是列表选中行的数据
				editFormRules: {
					fullName: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				clueFormVisible: false,//新增/修改界面是否显示,模态框是否展示
        clueActivityVisible: false,//绑定关联活动弹窗
        clueAssignVisible: false,//线索分配的弹框
				addFormRules: {
          fullName: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
        clueFormRules: {
          fullName: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增/修改界面数据/分配线索的数据
				clueForm: {
				  id: null,
          fullName: '',
					company: '',
					seller: {//营销人员
					  id: null
          },
          job: '',
					state: null
				}

			}
		},
		methods: {
		  /*转化商机
		  * */
      //1.当点击转化商机按钮时弹出弹框
      handleConvertOpportunities(){
        //先判断一下是否勾选了线索，是转化哪条线索
        if (this.handleSelectValue.length !=1){
          this.$message({message: '请选择一条线索后再进行操作', type: 'error'});
          return ;
        }
        this.clueBusinessVisible=true;//弹出弹框
        //将当前选中行的数据给businessData.clue,来做数据回显
        this.businessData.clue=this.handleSelectValue[0];
        //查询所有产品信息赋给products做选择下拉框
        this.getProducts();
      },
      //2.获取所有的产品来做商机的选择下拉框
      getProducts() {
        this.$http.get("/product")
            .then(result => {
              result=result.data;
              if (result.success){
                this.products=result.result;
              }else{
                this.$message({message: '获取产品失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '前端获取产品失败!'+result.message, type: 'error'});
        })
      },
      //3.当转化商机完成时需要将这份信息存到后端数据库，点击提交按钮要将数据传递给后端
      clueBusinessSubmit(){
        //开始进入加载等待
        this.businessFormLoading=true;
        this.$http.post("/clue/business",this.businessData)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '商机数据提交成功', type: 'success'});
                this.clueBusinessVisible = false;
                //重新从第一页开始查询
                this.query.currentPage=1;
                //重新查询线索展示到页面
                this.getClues();
                this.businessFormLoading=false;
              }else{
                this.$message({message: '商机数据提交失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '前端商机数据提交失败!'+result.message, type: 'error'});
        })
      },
      //当分配完线索时要把分配的这份数据保存到线索中：所属人，线索状态都要变更
      clueAssignSubmit(){
        //开始进入加载等待
        this.clueFormLoading=true;
        this.$http.post("/clue/assign",this.clueForm)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '线索分配成功', type: 'success'});
                this.clueAssignVisible = false;
                //重新从第一页开始查询
                this.query.currentPage=1;
                //重新查询线索展示到页面
                this.getClues();
                this.clueFormLoading=false;
              }else{
                this.$message({message: '线索分配失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '线索分配失败!'+result.message, type: 'error'});
        })
      },
		  //当点击分配线索时弹出弹框
      handleAssignClue(){
        // 点击分配之前要判断一下是否选中线索,如果没有选中线索,要提示用户请选择
        if(this.handleSelectValue.length != 1){
          this.$message({message: '请选择一条线索后再进行分配', type: 'error'});
          return ;
        }
        // this.handleSelectValue 是选中的所有行的数据
        //将选中的数据赋给双向绑定的线索分配页面数据项clueForm
        this.clueForm = this.handleSelectValue[0];

        // 弹出一个框
        this.clueAssignVisible = true;
        // 查询出所有的员工,并赋值给营销人员下拉框
        this.getEmployees();
      },
		  //当提交关联活动框的类容时
      clueActivitySubmit(){
        this.$http.post("/clue/activity",this.clueActivity)
            .then(result => {
              result = result.data;
              if(result.success){
                this.clueActivityVisible = false;
                this.$message({message: '添加活动成功', type: 'success'});
              }else{
                this.$message({message: '添加活动失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '添加活动失败!'+result.message, type: 'error'});
        })
      },

		  //当点击关联活动时
      handleClueActivity(index,row){
        //弹出弹框
        this.clueActivityVisible=true;
        this.clueActivity.clueId=row.id;
        //查询出所有的活动并用多选框的方式展示
        this.getActivities();
      },
		  //做绑定活动的多选框，首先得获取所有的活动
      getActivities(){
        this.$http.get("/activity/bind")
            .then(result => {
              result = result.data;
              if(result.success){
                console.log(result);
                this.activities = result.result;
              }else{
                this.$message({message: '获取活动列表失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '前端获取活动列表失败!', type: 'error'});
        })
      },
		  //查询所有员工:做部门经理的下拉框
      getEmployees(){
        this.$http.get("/employee")
            .then(result => {
              result=result.data;
              if (result.success){
                this.employees=result.result;
              }else {
                this.$message({
                  message: '获取员工数据失败'+result.message,
                  type: 'error'
                });
              }
            }).catch(result =>{
              this.$message({
              message: '获取员工数据失败',
              type: 'error'
          });
        })
      },
		  //高级查询，当输入关键字搜索时调用这个方法
      search(){
        this.query.currentPage=1;
        this.getClues();
      },
      //当当前页展示数据条数改变时，来重新查取数据
      handleSizeChange(val){
        //这里面带的参数就是当前页展示数据的条数
        this.query.pageSize=val;
        this.query.currentPage=1;
        this.getClues();
      },
      //当当前页改变时,来重新查取数据
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getClues();
			},
			//获取部门列表数据展示在页面
			getClues() {
        //开始加载
				this.listLoading = true;
				//NProgress.start();
				this.$http.post("/clue",this.query)
            .then(result =>{

              //result中装的是从后端返回来的数据，是个分页高级查询返回的数据PageList{total: rows:[]}
              result = result.data;
              // console.log(result);
              if (result.success){
                this.pageInfo = result.result;
                this.listLoading = false;
              }else {
                this.$message({
                  message: '查询分页失败'+result.message,
                  type: 'error'
                });
              }
            })
            .catch(result => {
              this.$message({
                message: '查询分页失败,没有进入后端数据库',
                type: 'error'
              })
            })
			},
			//删除操作
			handleDel: function (index, row) {
        //index是选中的行的下标，row是选中行的数据，是个Object对象
        // console.log(row)
				this.$confirm('确认删除该记录吗?', '提示', {type: 'warning'})
            .then(() => {//点击确认进入这个then中
              this.listLoading = true;
              this.$http.delete("/clue/"+row.id)
                  .then(result =>{//与后端成功联通进入这个then
                    result = result.data;
                    if (result.success){
                      this.$message({
                        message: '删除成功'+result.message,
                        type: 'success'
                      });
                      this.query.currentPage = 1;
                      this.getClues();
                      this.listLoading = false;
                    }else {
                      this.$message({
                        message: '删除失败'+result.message,
                        type: 'error'
                      });
                    }

                  })
				}).catch(result => {
          this.$message({
            message: '已取消删除',
            type: 'info'
          });
				});
			},
			//点击修改操作
			handleEdit: function (index, row) {
        //点击编辑按钮,弹出模态框,并回显编辑行的数据
				this.clueFormVisible = true;
				//回显数据
				this.clueForm = Object.assign({}, row);
				// debugger;
        //在新增页面可能选到管理者没有的情况，这样整个manager就会显示：manager:null
        //而不是一个对象的形式就会报错
				if (this.clueForm.manager == null){
				  this.clueForm.manager = {id: null}
        }
				/*当修改时为了回显父级部门，需要给this.clueForm.parent=[]拼一个数组的形式
				* 因为父级部门级联下拉框的值就是由各个父级部门的id组成的数组
				* 这里js是个弱类型的语言，变量类型可以随意转换
				* */
        //row.path='/1/2/22'
        if (row.path){
          let arrays = row.path.split("/");//['', '1', '2', '22']
          let ids = [];
          for (let i=1;i<arrays.length-1;i++){
            ids.push(parseInt(arrays[i]))//数组分割之后数组中的值还是字符串形式，需要转换成Integer类型
          }
          this.clueForm.parent = ids;
          console.log(ids)
        }
				//当点击修改操作时会获取所有员工来做部门领导的选择下拉框
				this.getEmployees();
        //当点击修改操作时会获取部门树来做父级部门的选择下拉框
        this.getDeptTree();
			},
			//点击新增操作
			handleAdd: function () {
        //点击新增按钮时弹出模态框
				this.clueFormVisible = true;
				//初始化数据，因为是双向绑定的，避免值累积
				this.clueForm = {
          id: null,
          name: '',
          intro: '',
          manager: {
            id: null
          },
          parent: {
            id: null
          },
          path: '',
          state: null
				};
        //当点击新增操作时会获取所有员工来做部门领导的选择下拉框
        this.getEmployees();
        //当点击新增操作时会获取部门树来做父级部门的选择下拉框
        this.getDeptTree();
			},
			//新增和修改完了之后的保存方法
			save: function () {
				this.$refs.clueForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							let para = Object.assign({}, this.clueForm);
							// debugger;
							// console.log(para)
              //当选择父部门之后，parent变成了一个数组，需要转换成对象才能和后端的匹配
              //如果选择了多级部门，最后一个部门才是这个部门真正的父级部门
              if (para.parent){//里面有值
                para.parent={"id": para.parent[para.parent.length-1]}
              }
							this.$http.put("/clue",para)
                  .then(result => {
                    result = result.data;
                    if (result.success){
                      this.$message({
                        message: '提交成功'+result.message,
                        type: 'success'
                      });
                      this.clueFormVisible = false;//关闭模态框
                      this.query.keyword=null;
                      this.query.currentPage = 1;//从第一页开始展示
                      this.getClues();//重新查询列表数据
                      this.saveLoading = false;//关闭加载等待
                    }else {
                      this.$message({
                        message: '提交失败'+result.message,
                        type: 'error'
                      });
                    }
                  }).catch(result =>{
                this.$message({
                  message: '前端提交失败',
                  type: 'info'
                });
              })
						});
					}
				});
			},
      handleSelectionChange: function (rows) {
        // debugger;
        //rows是自带的一个参数，是个数组，里面装的是选中行的数据
				this.handleSelectValue = rows;
			},
			//批量删除
			batchRemove: function () {
         // debugger;
        //1先获取要删除的部门的id
        var ids =[];
				ids = this.handleSelectValue.map(dept => dept.id);
				// //2.判断一下是否勾选了数据，如果没有勾选告诉用户应该勾选数据再删除
        // if (ids.length <1 ){
        //   this.$message({
        //     message: '请先勾选要删除的数据',
        //     type: 'error'
        //   });
        // }
        //3.给出友情提示
				this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
            .then(() => {//用户点击确认就进入这个then
            this.listLoading = true;//渲染页面加载等待
            //发送请求到后端删除数据
              this.$http.patch("/clue",ids)
                  .then(result => {
                    result=result.data;
                    if (result.success){
                      this.$message({
                        message: '批量删除成功',
                        type: 'success'
                      });
                      //从第一页从新回显部门列表数据
                      this.query.currentPage=1;
                      this.getClues();
                      this.listLoading=false//关闭加载
                    }else {
                      this.$message({
                        message: '批量删除失败'+result.message,
                        type: 'error'
                      });
                    }
                  })
				}).catch(result => {
          this.$message({
            message: '前端批量删除失败',
            type: 'error'
          });
				});
			}
		},
		mounted() {
			this.getClues();
		}
	}
</script>
<style scoped>

</style>